const http = require("http");
const fs = require("fs");
const path = require("path");

let ws = fs.createWriteStream(path.join(__dirname, "xxx.txt"));
let start = 0,
  limit = 27;
function download() {
  http.get(
    {
      hostname: "localhost",
      port: 3000,
      headers: {
        Range: `bytes=${start}-${start + limit}`
      }
    },
    res => {
      let total = res.headers["content-range"].split("/")[1];

      res.pipe(
        ws,
        { end: false }
      );
      // console.log(`start:${start};total:${total}`);
      if (total >= start) {
        start = start + limit + 1;
        setTimeout(() => {
          download();
        }, 1000);
      } else {
        ws.end();
      }
    }
  );
}
download();
